<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		* {
			margin: 0;
			padding: 0;
		}
		#game {
			width: 800px;
			height: 600px;
			background-image: url(images/sky.png);
			position: relative;
			overflow: hidden;
		}
		#bird {
			width: 34px;
			height: 24px;
			background: url(images/birds.png) -8px -11px no-repeat;
			position: absolute;
			top: 100px;
			left: 100px;
		}
	</style>
</head>
<body>
	<div id="game">
		<div id="bird"></div>
	</div>

	<script>
		var game = document.getElementById('game');
		var birdEle = document.getElementById('bird');

		var sky = {
			x: 5
		}
		var bird = {
			speechX: 5,
			speechY: 0,
			x: birdEle.offsetLeft,
			y: birdEle.offsetTop
		}
		var running = true;
		setInterval (function () {
			if (running) {
				// 让背景向做运动
				sky.x -= 5;
				game.style.backgroundPositionX = sky.x + 'px';
				// 让小鸟向下运动
				bird.speechY += 1;
				bird.y += bird.speechY;
				
				if (bird.y < 0) {
					bird.y = 0;
					running = false;
				}
				if (bird.y > game.offsetHeight - birdEle.offsetHeight) {
					bird.y = game.offsetHeight - birdEle.offsetHeight;
					running = false;
					console.log(game.offsetHeight);
				}
				birdEle.style.top = bird.y + 'px';
			}
			
		}, 30);
		// 点击文档时 小鸟向上运动
		document.onclick = function () {
			bird.speechY = -10;
		}

		// 创建管道
		function createPipe (position) {
			var pipe = {};
			pipe.x = position;

			pipe.uHeight = 200 + Math.random() * 100;
			pipe.dHeight = 600 - pipe.uHeight - 200;
			pipe.dTop = pipe.uHeight + 200;

			var uPipe = document.createElement('div');
			game.appendChild(uPipe);
			uPipe.style.width = '52px';
			uPipe.style.height = pipe.uHeight + 'px';
			uPipe.style.background = 'url(images/pipe2.png) no-repeat center bottom';
			uPipe.style.position = 'absolute';
			uPipe.style.left = pipe.x + 'px';
			uPipe.style.top = 0 + 'px';

			var dPipe = document.createElement('div');
			game.appendChild(dPipe);
			dPipe.style.width = '52px';
			dPipe.style.height = pipe.dHeight + 'px';
			dPipe.style.background = 'url(images/pipe1.png) no-repeat center top'; 
			dPipe.style.position = 'absolute';
			dPipe.style.left = pipe.x + 'px';
			dPipe.style.top = pipe.dTop + 'px';

			setInterval(function () {
				if (running) {
					pipe.x -= 2;
					uPipe.style.left = pipe.x + 'px';
					dPipe.style.left = pipe.x + 'px';
					if (pipe.x < -52) {
						pipe.x = 800;
					}
					var uCheck = (bird.x + 34 > pipe.x) && (Math.abs(pipe.x - bird.x) < 52) &&bird.y < pipe.uHeight;
					var dCheck = (bird.x + 34 > pipe.x) && (Math.abs(pipe.x - bird.x) < 52) &&bird.y > pipe.uHeight + 200;
					
					if (uCheck || dCheck) {
						running = false;
					}
				}
				
			}, 30)

		}
		createPipe(400);
		createPipe(600);
		createPipe(800);
		createPipe(1000);
	</script>
</body>
</html>